package apigen

import (
	"errors"
	"fmt"
	"path/filepath"
	"strings"
	"text/template"

	"gitee.com/realjf/wob/tools/bctl/util/pathx"
	"github.com/logrusorgru/aurora"
	"github.com/urfave/cli"
)

const apiTemplate = `
package api

import (
	"github.com/gin-gonic/gin"
)

func {{.camelName}}(c *gin.Context) {
	c.JSON(200, gin.H{})
}
`

// ApiCommand create api template file
func ApiCommand(c *cli.Context) error {
	apiFile := c.String("o")
	if len(apiFile) == 0 {
		return errors.New("missing -o")
	}
	fp, err := pathx.CreateIfNotExist(apiFile)
	if err != nil {
		return err
	}
	defer fp.Close()

	home := c.String("home")
	if len(home) > 0 {
		pathx.RegisterBctlHome(home)
	}

	text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
	if err != nil {
		return err
	}

	baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
	if strings.HasSuffix(strings.ToLower(baseName), "-api") {
		baseName = baseName[:len(baseName)-4]
	} else if strings.HasSuffix(strings.ToLower(baseName), "api") {
		baseName = baseName[:len(baseName)-3]
	}

	t := template.Must(template.New("etcTemplate").Parse(text))
	if err := t.Execute(fp, map[string]string{
		"gitUser":     getGitName(),
		"gitEmail":    getGitEmail(),
		"camelName": CamelString(baseName),
	}); err != nil {
		return err
	}

	fmt.Println(aurora.Green("Done."))
	return nil
}
